package top.hcode.hoj;

import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import org.nutz.lang.Files;
import top.hcode.hoj.common.LazyDao;
import top.hcode.hoj.pojo.entity.org.Org;
import top.hcode.hoj.pojo.entity.org.OrgUser;
import top.hcode.hoj.utils.Constants;

import java.io.File;
import java.util.List;

/**
 * @author orangej
 * @since 2025/2/21
 */
public class ExportAllClassUserApp extends BaseDbApp {
    private static LazyDao dao;
    private static final String outPath = "d:\\0221\\";

    public static void main(String[] args) {
        dao = buildLazyDao();

        List<Org> schoolList = queryAllSchool();
        for (Org school : schoolList) {
            exportSchool(school);
        }
    }

    private static void exportSchool(Org school) {
        List<Org> campusList = queryByOrgType(school.getTreeCode(), Constants.OrgType.CAMPUS);
        for (Org campus : campusList) {
            System.out.printf("school: %s, campus: %s\n", school.getOrgName(), campus.getOrgName());
            exportCampus(school, campus);
        }
    }

    private static void exportCampus(Org school, Org campus) {
        List<Org> classList = queryByOrgType(campus.getTreeCode(), Constants.OrgType.CLASS);
        classList.parallelStream().forEach(clazz -> exportClass(school, campus, clazz));
    }

    private static void exportClass(Org school, Org campus, Org clazz) {
        List<OrgUser> orgUserList = queryClassStudent(clazz.getId());

        // export to csv, path is d:\\1124\\schoolName\\campusName\\className.csv
        String fileName = outPath + school.getOrgName() + "\\" + campus.getOrgName() + "\\" + clazz.getOrgName() + ".csv";
        File csvFile = new File(fileName);
        Files.makeDir(csvFile.getParentFile());

        CsvWriter writer = CsvUtil.getWriter(fileName, CharsetUtil.CHARSET_UTF_8)
                .setAlwaysDelimitText(false)
                .writeHeaderLine("账号", "姓名");
        for (OrgUser user : orgUserList) {
            writer.writeLine(user.getUsername(), user.getRealName());
        }

        writer.flush();
        writer.close();
    }

    private static List<OrgUser> queryClassStudent(String classId) {
        return dao.selectList(OrgUser.class,
                "select username, real_name from org_user where id in " +
                        "(select user_id from class_has_user where org_id = ? and user_type = 0)", classId);
    }

    private static List<Org> queryAllSchool() {
        return dao.selectList(Org.class, "select * from org where id = '1892805138413035521' and org_type = ?", Constants.OrgType.SCHOOL.getType());
    }

    static List<Org> queryByOrgType(String parentCode, Constants.OrgType orgType) {
        return dao.selectList(Org.class,
                "select * from org where org_type = ? and tree_code like ?",
                orgType.getType(), parentCode + "%");
    }
}
